package com.foreveross.crawl;

import org.apache.log4j.Logger;

import com.foreveross.crawl.counter.Counter;
import com.foreveross.crawl.counter.CrawlEngineCounterManager;

/**
 * 抓取引擎监控器
 * 职责：监控是否有任务需要执行
 * <p>尚未任务组监控,接下来优化
 * @author xiangsf
 * @since 2013-1-31
 */
public class CrawlEngineMonitor {
	
	 public final static String MonitorAllTaskCount = "crawlEngineMonitor-allTaskCount";
	 public final static String MonitorAllDoneTaskCount = "crawlEngineMonitor-allDoneTaskCount";
	 public final static String MonitorAllFailTaskCount = "crawlEngineMonitor-allFailTaskCount";
	 public final static String MonitorAllDataCount = "crawlEngineMonitor-allDataCount";

	 
	private static CrawlEngineMonitor _instance = new CrawlEngineMonitor();
	/**
	 * 任务计数器
	 */
	public Counter allTaskCount=null;
	  
	/**
	 * 数据计数器
	 */
	public Counter allDataCount=null;
	
	/**
	 * 成功执行的任务计数器
	 */
	public Counter allDoneTaskCount=null;
	
	/**
	 * 所有失败的任务计数器
	 */
	public Counter allFailTaskCount=null;
	
	
	public static Logger _log = Logger.getLogger(CrawlEngineStartUp.class);
	
	public static CrawlEngineMonitor getInstance(){
		return _instance;
	}
	/**
	 * 实例化的时候，同时实例化所有的计数器
	 */
	private CrawlEngineMonitor(){
		allTaskCount = CrawlEngineCounterManager.registerNewCounter(MonitorAllTaskCount);
		allDoneTaskCount = CrawlEngineCounterManager.registerNewCounter(MonitorAllDoneTaskCount);
		allFailTaskCount = CrawlEngineCounterManager.registerNewCounter(MonitorAllFailTaskCount);
		allDataCount = CrawlEngineCounterManager.registerNewCounter(MonitorAllDataCount);
	}
	
	public void allTaskCount(){
		allTaskCount.count();
	}
	public void allDoneTaskCount(){
		allDoneTaskCount.count();
	}
	public void allFailTaskCount(){
		allFailTaskCount.count();
	}
	public void allDataCount(int crawlCount){
		allDataCount.countNum(crawlCount);
	}
	/**
	 * 注销抓取任务监控器
	 * @return
	 * @throws Exception 
	 */
	public void destory(){
		CrawlEngineCounterManager.removeCounter(MonitorAllTaskCount);
		CrawlEngineCounterManager.removeCounter(MonitorAllDoneTaskCount);
		CrawlEngineCounterManager.removeCounter(MonitorAllFailTaskCount);
		CrawlEngineCounterManager.removeCounter(MonitorAllDataCount);
	}
	
	
	
	public void show() {
		_log.info("总共执行了"+ allTaskCount.getCount() + "条任务");
		_log.info("成功执行了"+ allDoneTaskCount.getCount()+"条任务");
		_log.info("失败执行了"+ allFailTaskCount.getCount()+"条任务");
		_log.info("总共抓取了" + allDataCount.getCount()+"条数据");
	}
		
}
